package com.bdf.congcache;

import com.bdf.congcache.access.AbstractCongCacheAccess;
import com.bdf.congcache.access.CongCacheAccess;
import com.bdf.congcache.access.ICongCacheAccess;
import com.bdf.congcache.access.exception.CacheException;
import com.bdf.congcache.core.control.ContextCache;
import com.bdf.congcache.core.control.ContextCacheManager;

import javax.naming.Context;
import java.util.Properties;

/**
 * @Author 田培融
 * @Description 入口类
 * @Date 13:54 2019/7/10
 * @Param 
 * @return 
 **/
public abstract class CongCache<K,V> extends AbstractCongCacheAccess<K,V> implements ICongCacheAccess {

    // 配置文件的名称
    private static String configFilename = null;

    // 配置文件
    private static Properties configProps =null;

    // 上下文件管理器
    private static ContextCacheManager cacheMgr ;


    protected CongCache(ContextCache<K, V> cacheControl) {
        super(cacheControl);
    }

    public static void setConfigFilename(String configFilename){CongCache.configFilename = configFilename;}

    public static void setConfigProperties(Properties properties) {CongCache.configProps = properties;}




    // 关闭服务，将上下文管理器设置为null
    //TODO 关闭服务功能先放一下。。。。。。
    public static void shutdown(){
        synchronized (CongCache.class){
            if (cacheMgr !=null && cacheMgr.isInitialized()){

            }
        }
    }


    // 获取一个缓存对象 getInstance()
    public static <K,V> CongCacheAccess<K,V> getInstance(String cacheName) throws CacheException  {
        ContextCacheManager cacheManager = getCacheManager();
        ContextCache<K, V> cache = cacheManager.getCache(cacheName);
        return new CongCacheAccess<K,V>(cache);
    }

    private static ContextCacheManager getCacheManager() throws CacheException{
        // 加入类锁
        synchronized (CongCache.class){
            // 判断 ContextCacheManager 是否被创建出来
            if (cacheMgr == null || !cacheMgr.isInitialized())
            {
                if (configProps != null)
                {
                    cacheMgr = ContextCacheManager.getUnconfiguredInstance();
                    cacheMgr.configure(configProps);
                }
                // 自定义配置文件
                else if (configFilename!=null){
                    cacheMgr = ContextCacheManager.getUnconfiguredInstance();
                    cacheMgr.configure(configFilename);
                }else {
                    cacheMgr = ContextCacheManager.getInstance();
                }
            }
            return cacheMgr;
        }
    }





}
